import aiohttp
# asyncio  这是异步模块  异步技术是开启协程  是开销最小的技术
# 为了不阻塞 函数的执行  （网络请求 数据库io）

# 同步
import requests
import time
import asyncio
import aiohttp
#
# urls = [f'https://httpbin.org/get?age={i}' for i in range(1)]
#
# for url in urls:
#     start = time.time()
#     response = requests.get(url)
#
#     print(response.json())
#     print(time.time() - start)


# 异步

# async def main():
#     print('start')
#     await asyncio.sleep(5)
#     print('结束')
#
# # 返回一个协程
# main = main()
# #启动异步
# asyncio.run(main)


# 开起多个 异步
# async def main1():
#     print('程序1开始')
#     await asyncio.sleep(3)
#     print('程序1结束')
#
# async def main2():
#     print('程序2开始')
#     await asyncio.sleep(5)
#     print('程序2结束')
#
# async def main():
#     start = time.time()
#     await asyncio.gather(main1(), main2())
#     time1 = time.time() - start
#     print(time1)
#
# asyncio.run(main())
#
#
# async def fun(num):
#     print(num,'start')
#     await asyncio.sleep(1)
#     print(num,'end')
#
# async def main3():
#     fun1 = [fun(num)  for num in range(10)]
#     await asyncio.gather(*fun1)
# asyncio.run(main3())


# 发起异步请求

async def mian():
    async with aiohttp.ClientSession() as session:
         async with session.get('https://httpbin.org/get?age=1') as response:
            print(await response.json())

start = time.time()
asyncio.run(mian())
print(time.time()-start)








async def get_res(session,url):
    async with session.get(url) as response:
        return await response.json()

async def mian1():
    async with aiohttp.ClientSession() as session:
        values = await asyncio.gather(*[get_res(session,f'https://httpbin.org/get?age={i}') for i in range(10)])
        for v in values:
            print(v)

start = time.time()
asyncio.run(mian1())
print(time.time()-start)
